<?php
namespace Admin\Controller;
use Think\Controller;
class GoodsController extends AdminController {
    public function index(){
        $Goods = M('Goods');//实例化AdminUser对象
        $count = $Goods->count();// 查询满足要求的总记录数
        $itemNum = 6; //每页显示的记录数
        $show = c_page($count,'件商品');

        //page方法分页
        $data = $Goods
                ->alias('g')
                ->field('g.*,c.name as category_name')
                ->join('__CATEGORY__ as c on g.category_id = c.id','left')
                ->order('u_time desc, id desc')
                ->page(I('get.p',1) . ',' . $itemNum)
                ->select();

        //标题20个字
        foreach ($data as $k => $v){
            $data[$k]['title'] = subtext(strip_tags($v['title']),20,'...');
        }


        if(IS_AJAX){
            $json['data'] = $data;
            $json['page'] = $show;
            $this->ajaxReturn($json);
        }else{
            $this->assign('title','商品列表');//标题
            $this->assign('data',$data);// 赋值数据集
            $this->assign('page',$show);// 赋值分页输出
            $this->display();
        }
    }


    /**
     * 添加
     */
    public function add(){
        if(IS_POST){
            $data = I('post.');

            $data['content'] = I('post.content','','clear_js');
            foreach ($data['attr'] as $k => $v) {
                if($v){
                    $attr[$v] = (int)$data['attr_number'][$k];
                    $data['number'] += (int)$data['attr_number'][$k];
                }
            }
//            $attr[$v] = (int)$data['attr_number'][$k];
            $data['attr'] = json_encode($attr);
            $data['color'] = str_replace('，', ',', $data['color']);
            $Goods = D('Goods');
            $Goods->setData($data);

            $res = $Goods->insertDb();
            if($res){
                $this->success('添加成功',U('index'));
            }else {
                $this->error('添加失败：' . $Goods->getError());
            }

        }else{
            $Category = M("Category")->order('sort asc,u_time desc,id asc')->select();
            $Category = get_category($Category,GOODS_PID);
            $this->assign('title','商品添加');//标题
            $this->assign('category',$Category);//分类下拉框
            $this->display();
        }
    }


    //$id 表示URL问号后面的id字段
    public function edit($id = 0){
        if($id < 1){
            $this->error('参数错误');
        }
        if(IS_POST){
            $data = I('post.');
            $data['content'] = I('post.content','','clear_js');
            foreach ($data['attr'] as $k => $v) {
                if($v){
                    $attr[$v] = (int)$data['attr_number'][$k];
                    $data['number'] += (int)$data['attr_number'][$k];
                }
            }
//            $attr[$v] = (int)$data['attr_number'][$k];
            $data['attr'] = json_encode($attr);
            $data['color'] = str_replace('，', ',', $data['color']);
            $Goods = D('Goods');
            $Goods->setData($data);
            //记得报错
            $res = $Goods->updateDb();
            if($res !== false){
                $this->success('修改成功',U('index'));
            }else{
                $this->error('修改失败 '.$Goods->getError());
            }
            exit;//post到数据 就执行结束
        }else{
            $one = M('Goods')
                ->alias('g')
                ->field('g.*,gi.content')
                ->join('__GOODS_INFO__ as gi on g.id = gi.goods_id','left')
                ->find($id);
            $Category = M("Category")->order('sort asc,u_time desc,id asc')->select();
            $Category = get_category($Category,GOODS_PID);
            $this->assign('title','商品修改');//标题
            $this->assign('category',$Category);//分类下拉框
            $this->assign('one',$one);//该ID的商品
            $this->display();
        }

    }

    public function delete($id){
        if($id<1){
            $this->error('参数错误,至少选择一条数据');
        }
        //附表不报错了。
        if(!is_array($id)){
            $res = M('Goods')->delete($id);
            $res1 = M('GoodsInfo')->delete($id);
        }else{
            $wh['id'] = array('in',implode(',', $id));
            $res = M('Goods')->where($wh)->delete();
            $res1 = M('GoodsInfo')->where($wh)->delete();
        }
        if($res !== false){
            $this->success('删除成功',U('index'));
        }else{
            $this->error('删除失败：',U('index'));
        }
    }

    //服务器异步通知页面路径 当用户一支付成功，立刻后台异步通知商城
    //做接口给支付表调用
    // 当用户一支付成功，立刻后台异步通知商城 就是 支付宝访问 异步通知页面路径 传递参数过来【post】
    public function yb_notify_url(){
        @file_put_contents('gg.txt', json_encode(I()));
        $alipay_config = C('ALIPAY_CONFIG');//获取 键名为ALIPAY_CONFIG的配置
        // require_once("lib/alipay_notify.class.php");
        vendor("alipay.lib.alipay_notify#class");

        //计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result){
            //验证成功
            //商户订单号

            $wh['order_id'] = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];


            if($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {
                //成功  把订单状态改为3 已支付
                $data['status'] = 3;
                $data['u_time'] = time();
                $res = M('Order')->where($wh)->data($data)->save();
                if($res !== false){
                    echo "success";   //请不要修改或删除
                }else{
                    echo "fail";
                }
            }
        }
        else {
            //验证失败
            echo "fail";
        }
    }

    public function upload_img($type=0)
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 2 * 1024 * 1024 ;// 设置附件上传大小 2m
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        // $upload->savePath = 'Goods/'; // 设置附件上传（子）目录
        $upload->subName = array('date','Y/m/d');
        // 上传文件
        $info = $upload->uploadOne($_FILES['file']);
//        dump($info);
//        exit;
        if(!$info) { // 上传错误提示错误信息
            $this->ajaxReturn(array("error"=>$upload->getError()));

        }else{ // 上传成功
            $pic_url = 'Uploads/'.$info['savepath'].$info['savename'];
            $image = new \Think\Image();
            $img = $image->open($pic_url);
            // $img1 = clone($img);
//            exit;

            $water = M('Water')->find();
//          $thumb = get_thumb($pic_url);//_thumb

        /*  //缩小 图片
            //生成一个缩放后填充大小150*150的缩略图并保存为thumb.jpg
            $image->open($water['mark_img']);
            $image->thumb(150, 150,\Think\Image::IMAGE_THUMB_FILLED)->save('./thumb.jpg');*/
            $waterImgUrl = strstr($water['mark_img'],'Uploads');
//            var_dump($waterImgUrl);
//            exit;

            if(!$type){
                $img->thumb(243, 334,3)->water($waterImgUrl,$water['mark_pos'],$water['alpha'])->save($pic_url);
            }else{
                $img->thumb(490, 490,3)->ater($waterImgUrl,$water['mark_pos'],$water['alpha'])->save($pic_url);
            }
            // $img->thumb(400, 800,3)->water($water['mark_img'])->save($thumb);
            // $img1->water($water['mark_img'])->save($pic_url);
            $this->ajaxReturn(array('error'=>'0','pic'=>__ROOT__.'/'.$pic_url,'name'=>$info['savename']));
        }
    }

}
?>